﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using Stock.Dal;
using Stock.Model;

namespace Stock.Bl
{
    public class SumWeekBll
    {
        private readonly StockOptHisDal stockOptHisDal = new StockOptHisDal();
        private readonly GainHisDal gainHisDal = new GainHisDal();

        /// <summary>
        /// 取得起始日期
        /// </summary>
        /// <returns></returns>
        public DateTime getMinOptDate()
        {
            string back = stockOptHisDal.GetMinDate();
            return DateTime.ParseExact(back, "yyyy-MM-dd", CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// 查询范围内进入账户的资金（大于开始日期，小于等于结束日期）
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public decimal getInMoneyBeforDate(DateTime dtStart, DateTime dtEnd)
        {
            decimal back = stockOptHisDal.getInMoneyList(dtStart.ToString("yyyy-MM-dd"), dtEnd.ToString("yyyy-MM-dd"), "in");

            return back;
        }

        /// <summary>
        /// 在日期前的账户的余额（包括日期）
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public decimal getRemainingMoneyBeforDate(DateTime dt)
        {
            decimal back = stockOptHisDal.getRemainingMoneyList(dt.ToString("yyyy-MM-dd"));

            return back;
        }

        /// <summary>
        /// 取得星期五的列表
        /// </summary>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <returns></returns>
        public List<DateTime> getFridayList(DateTime dtStart, DateTime dtEnd)
        {
            List<DateTime> back = new List<DateTime>();
            for (DateTime dt = dtStart; dt <= dtEnd; )
            {
                if (dt.DayOfWeek == DayOfWeek.Friday)
                    back.Add(dt);
                if (back.Count == 0)
                {
                    dt = dt.AddDays(1);
                }
                else
                {
                    dt = dt.AddDays(7);
                }
            }

            return back;
        }

        public List<DateTime> getFridayList()
        {
            List<DateTime> back = new List<DateTime>();

            DateTime startDate = getStartDate();

            back = getFridayList(startDate.AddDays(1), DateTime.Now);

            return back;
        }

        public void saveCalcResult(DateTime startDate, DateTime ddt, Rate rate)
        {
            GainHisEntity gainHisEntity = gainHisDal.GetModel(startDate.ToString("yyyy-MM-dd"));

            decimal inMoney = getInMoneyBeforDate(startDate, ddt);
            gainHisEntity.BankAmount = gainHisEntity.BankAmount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.BankAmount + inMoney, startDate, ddt, rate.BankRate / 100);//TODO
            gainHisEntity.BankRate = rate.BankRate / 100;

            gainHisEntity.CalcDate = ddt.ToString("yyyy-MM-dd");

            gainHisEntity.FactSumAmount = getRemainingMoneyBeforDate(ddt) + getStockSumMoneyBeforDate(ddt);//TODO

            gainHisEntity.Pre0Amount = gainHisEntity.Pre0Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre0Amount + inMoney, startDate, ddt, rate.Pre0Rate / 100);//TODO
            gainHisEntity.Pre0 = rate.Pre0Rate / 100;

            gainHisEntity.Pre1Amount = gainHisEntity.Pre1Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre1Amount + inMoney, startDate, ddt, rate.Pre1Rate / 100);//TODO
            gainHisEntity.Pre1 = rate.Pre1Rate / 100;

            gainHisEntity.Pre2Amount = gainHisEntity.Pre2Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre2Amount + inMoney, startDate, ddt, rate.Pre2Rate / 100);//TODO
            gainHisEntity.Pre2 = rate.Pre2Rate / 100;

            gainHisEntity.Pre3Amount = gainHisEntity.Pre3Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre3Amount + inMoney, startDate, ddt, rate.Pre3Rate / 100);//TODO
            gainHisEntity.Pre3 = rate.Pre3Rate / 100;

            gainHisDal.Add(gainHisEntity);
        }

        //public void bactchCalcGain()
        //{
        //    DateTime startDate;
        //    Rate rate = new Rate();

        //    GainHisEntity gainHisEntity = new GainHisEntity();
        //    //1、判断是否有历史数据（有历史数据的情况，按DB里面的数据为基准）
        //    if (true)
        //    {
        //        // Set Rate To LastData's Rate TODO

        //        startDate = DateTime.ParseExact("2011-08-01", "yyyy-MM-dd", CultureInfo.InvariantCulture);//TODO LastData's Rate;
        //    }
        //    else
        //    {
        //        startDate = getMinOptDate().AddDays(-1);
        //    }

        //    // 取得周5的列表
        //    List<DateTime> sd = getFridayList(startDate, DateTime.Now);

        //    foreach (DateTime ddt in sd)
        //    {
        //        //取得开始日期到周5的入账

        //        decimal inMoney = getInMoneyBeforDate(startDate, ddt);
        //        gainHisEntity.BankAmount = gainHisEntity.BankAmount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.BankAmount + inMoney, startDate, ddt, rate.BankRate / 100);//TODO
        //        gainHisEntity.BankRate = rate.BankRate;

        //        gainHisEntity.CalcDate = ddt.ToString("yyyy-MM-dd");

        //        gainHisEntity.FactSumAmount = getRemainingMoneyBeforDate(ddt) + getStockSumMoneyBeforDate(ddt);//TODO

        //        gainHisEntity.Pre0Amount = gainHisEntity.Pre0Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre0Amount + inMoney, startDate, ddt, rate.Pre0Rate / 100);//TODO
        //        gainHisEntity.Pre0 = rate.Pre0Rate;

        //        gainHisEntity.Pre1Amount = gainHisEntity.Pre1Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre1Amount + inMoney, startDate, ddt, rate.Pre1Rate / 100);//TODO
        //        gainHisEntity.Pre1 = rate.Pre1Rate;

        //        gainHisEntity.Pre2Amount = gainHisEntity.Pre2Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre2Amount + inMoney, startDate, ddt, rate.Pre2Rate / 100);//TODO
        //        gainHisEntity.Pre2 = rate.Pre2Rate;

        //        gainHisEntity.Pre3Amount = gainHisEntity.Pre3Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre3Amount + inMoney, startDate, ddt, rate.Pre3Rate / 100);//TODO
        //        gainHisEntity.Pre3 = rate.Pre3Rate;

        //        startDate = ddt;
        //    }
        //}

        private decimal getStockSumMoneyBeforDate(DateTime ddt)
        {
            //取得份数不为0的股票的List
            List<string[]> listStock = stockOptHisDal.getStockList(ddt.ToString("yyyy-MM-dd"));

            decimal back = 0m;
            foreach (string[] stockId in listStock)
            {
                string filePath = makeFilePath(stockId[0]);
                decimal price = Common.CaclCommon.getStockPriceByDate(ddt.ToString("yyyy-MM-dd"), filePath);

                back += decimal.Parse(stockId[1]) * price;
            }
            return back;
        }

        private string makeFilePath(string stockId)
        {
            if (stockId.StartsWith("6"))
            {
                return "C:\\金鼎智赢\\T0002\\export\\SH" + stockId + ".txt";
            }
            else
            {
                return "C:\\金鼎智赢\\T0002\\export\\SZ" + stockId + ".txt";
            }
        }

        internal DateTime getStartDate()
        {
            DateTime startDate;
            startDate = getMinOptDate().AddDays(-1);
            DateTime gainMaxDate = gainHisDal.GetMaxDate();

            if (gainMaxDate > startDate)
                startDate = gainMaxDate;

            return startDate;
        }

        internal List<GainHisEntity> getGainHisList()
        {
            DataSet ds = gainHisDal.GetDataList();

            return dataTableToList(ds.Tables[0]);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        private List<GainHisEntity> dataTableToList(DataTable dt)
        {
            List<GainHisEntity> modelList = new List<GainHisEntity>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                GainHisEntity model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new GainHisEntity();
                    if (dt.Rows[n]["ID"] != null && dt.Rows[n]["ID"].ToString() != "")
                    {
                        model.ID = int.Parse(dt.Rows[n]["ID"].ToString());
                    }
                    if (dt.Rows[n]["BankRate"] != null && dt.Rows[n]["BankRate"].ToString() != "")
                    {
                        model.BankRate = decimal.Parse(dt.Rows[n]["BankRate"].ToString());
                    }
                    if (dt.Rows[n]["Pre0"] != null && dt.Rows[n]["Pre0"].ToString() != "")
                    {
                        model.Pre0 = decimal.Parse(dt.Rows[n]["Pre0"].ToString());
                    }
                    if (dt.Rows[n]["Pre1"] != null && dt.Rows[n]["Pre1"].ToString() != "")
                    {
                        model.Pre1 = decimal.Parse(dt.Rows[n]["Pre1"].ToString());
                    }
                    if (dt.Rows[n]["Pre2"] != null && dt.Rows[n]["Pre2"].ToString() != "")
                    {
                        model.Pre2 = decimal.Parse(dt.Rows[n]["Pre2"].ToString());
                    }
                    if (dt.Rows[n]["Pre3"] != null && dt.Rows[n]["Pre3"].ToString() != "")
                    {
                        model.Pre3 = decimal.Parse(dt.Rows[n]["Pre3"].ToString());
                    }
                    if (dt.Rows[n]["CalcDate"] != null && dt.Rows[n]["CalcDate"].ToString() != "")
                    {
                        model.CalcDate = dt.Rows[n]["CalcDate"].ToString();
                    }
                    if (dt.Rows[n]["BankAmount"] != null && dt.Rows[n]["BankAmount"].ToString() != "")
                    {
                        model.BankAmount = decimal.Parse(dt.Rows[n]["BankAmount"].ToString());
                    }
                    if (dt.Rows[n]["Pre0Amount"] != null && dt.Rows[n]["Pre0Amount"].ToString() != "")
                    {
                        model.Pre0Amount = decimal.Parse(dt.Rows[n]["Pre0Amount"].ToString());
                    }
                    if (dt.Rows[n]["Pre1Amount"] != null && dt.Rows[n]["Pre1Amount"].ToString() != "")
                    {
                        model.Pre1Amount = decimal.Parse(dt.Rows[n]["Pre1Amount"].ToString());
                    }
                    if (dt.Rows[n]["Pre2Amount"] != null && dt.Rows[n]["Pre2Amount"].ToString() != "")
                    {
                        model.Pre2Amount = decimal.Parse(dt.Rows[n]["Pre2Amount"].ToString());
                    }
                    if (dt.Rows[n]["Pre3Amount"] != null && dt.Rows[n]["Pre3Amount"].ToString() != "")
                    {
                        model.Pre3Amount = decimal.Parse(dt.Rows[n]["Pre3Amount"].ToString());
                    }
                    if (dt.Rows[n]["FactSumAmount"] != null && dt.Rows[n]["FactSumAmount"].ToString() != "")
                    {
                        model.FactSumAmount = decimal.Parse(dt.Rows[n]["FactSumAmount"].ToString());
                    }
                    modelList.Add(model);
                }
            }
            return modelList;
        }
    }
}